package flex.cc.basicinformation.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import flex.cc.basicinformation.vo.ServiceProviderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.base.enums.ErrorCodeEnum;
import flex.cc.basicinformation.dao.ServiceProviderCountryDao;
import flex.cc.basicinformation.dao.ServiceProviderDao;
import flex.cc.basicinformation.dao.ServiceProviderDataDao;
import flex.cc.basicinformation.entity.ServiceProviderCountryEntity;
import flex.cc.basicinformation.entity.ServiceProviderDataEntity;
import flex.cc.basicinformation.entity.ServiceProviderEntity;
import flex.cc.basicinformation.service.ServiceProviderService;
import flex.cc.basicinformation.vo.DynamicItem;
import flex.cc.system.dao.DictCodeDao;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.uac.exceptions.UacBizException;
import groovy.util.logging.Slf4j;

@Service("ServiceProviderServiceImpl")
@Slf4j
public class ServiceProviderServiceImpl extends ServiceImpl<ServiceProviderDao, ServiceProviderEntity> implements ServiceProviderService {

    @Autowired
	private ServiceProviderDao serviceProviderDao;

    @Autowired
	private ServiceProviderDataDao serviceProviderDataDao;

    @Autowired
	private ServiceProviderCountryDao serviceProviderCountryDao;

    @Autowired
	private DictCodeDao dictCodeDao;

    @Override
    public ServiceProviderEntity getOneByParams(Map<String, Object> params) {
        return serviceProviderDao.getOneByParams(params);
    }

	@Override
	public IPage<ServiceProviderEntity> queryServiceProviderPage(ServiceProviderEntity service) {
		 List<String> listItem=new ArrayList<String>();
		 if(!PublicUtil.isEmpty(service.getServiceItem())) {
			 StringTokenizer st=new StringTokenizer(service.getServiceItem(),",");
				while(st.hasMoreTokens()){
					listItem.add(st.nextToken());
		        }
		 }
		 service.setServiceItemList(listItem);
		IPage<ServiceProviderEntity> page = serviceProviderDao.queryServiceProviderPage(new Page(service.getPageNum(),service.getPageSize()),service);
		List<ServiceProviderEntity> list= page.getRecords();
		if (list!=null&&list.size()>0) {
			Map<String,String> map=new HashMap<String,String>();
			Map<String,String> map1=new HashMap<String,String>();
			List<String> lists=new ArrayList<String>();
			for(ServiceProviderEntity facilitator:list) {
				lists.add(facilitator.getId()+"");
			}
			String s=this.getSqlInString(lists);
			List<ServiceProviderDataEntity> urlList= serviceProviderDataDao.getServiceProviderUrl(this.getSqlInString(lists));
			DictCodeEntity code=new DictCodeEntity();
			code.setTypeCode("serviceItem");
			List<DictCodeEntity> dictList = dictCodeDao.getdictCodeList(code);
			if(dictList!=null&&dictList.size()>0) {
				for (DictCodeEntity d : dictList) {
					map1.put(d.getCode(),d.getValue());
				}
			}
			for (ServiceProviderDataEntity url : urlList) {
				map.put(url.getYwid(),url.getUrl());
			}
			for(ServiceProviderEntity serviceVo:list) {
				serviceVo.setUrl(map.get(serviceVo.getId()+""));
				if(!PublicUtil.isEmpty(serviceVo.getServiceCode())) {
					serviceVo.setServiceName(serviceVo.getServiceName()+"("+serviceVo.getServiceCode()+")");
				}
				if(!PublicUtil.isEmpty(serviceVo.getServiceItem()) ) {
					String[] serviceItem=serviceVo.getServiceItem().split(",");
					String cbkind="";
					for(int i = 0; i < serviceItem.length; i++) {
	   	    			if(i == serviceItem.length-1){
	   	    				cbkind += map1.get(serviceItem[i]) ;
	   	  			    }else{
	   	  			    	cbkind += map1.get(serviceItem[i]) + "," ;
	   	  			    }
	   	    		 }
					serviceVo.setServiceItem(cbkind);
				}
			}
		}

		return page;
	}


	@Override
	public void saveServiceProvider(ServiceProviderEntity service, LoginAuthDto loginAuthDto) {
		Date currentDate = new Date();
		if(PublicUtil.isEmpty(service.getId())) {
			List<ServiceProviderEntity>channelList=serviceProviderDao.selectServiceName(service);
			if(channelList!=null&&channelList.size()>0){
				 throw new UacBizException(ErrorCodeEnum.CHANNE10011025, service.getServiceName());
			}else {
				String urlType=	removaDuplicate(service.getDynamicItem());
			   if("1".equals(urlType)) {
					throw new UacBizException(ErrorCodeEnum.CHANNE10011026, "");
			   }
			   if (!PublicUtil.isEmpty(service.getAddrCounty())) {
				   if(!PublicUtil.isEmpty(service.getAddrCounty().get("province"))) {
					   String[] province=service.getAddrCounty().get("province").split(",");
					   String provinceName="";
					   String provinceCode="";
					   for(int i = 0; i < province.length; i++) {
		   	    			if(i == province.length-1){
		   	    				provinceCode +=province[i].split("-")[0] ;
		   	    				provinceName +=province[i].split("-")[1] ;
		   	  			    }else{
		   	  			        provinceCode += province[i].split("-")[0] + "," ;
		   	  			        provinceName += province[i].split("-")[1] + "," ;
		   	  			    }
		   	    		}
					   service.setProvinceCode(provinceCode);
					   service.setProvinceName(provinceName);
				   }
                   if(!PublicUtil.isEmpty(service.getAddrCounty().get("city"))) {
                	   String[] city=service.getAddrCounty().get("city").split(",");

                	   String cityName="";
					   String cityCode="";
					   for(int i = 0; i < city.length; i++) {
		   	    			if(i == city.length-1){
		   	    				cityCode +=city[i].split("-")[0] ;
		   	    				cityName +=city[i].split("-")[1] ;
		   	  			    }else{
				   	  			 cityCode += city[i].split("-")[0] + "," ;
				   	  			 cityName += city[i].split("-")[1] + "," ;
		   	  			    }
		   	    		}
                	    service.setCityCode(cityCode);
                	    service.setCityName(cityName);
				   }
				   if(!PublicUtil.isEmpty(service.getAddrCounty().get("area"))) {
					   String[] area=service.getAddrCounty().get("area").split(",");

					   String areaName="";
					   String areaCode="";
					   for(int i = 0; i < area.length; i++) {
		   	    			if(i == area.length-1){
		   	    				areaCode +=area[i].split("-")[0] ;
		   	    				areaName +=area[i].split("-")[1] ;
		   	  			    }else{
		   	  			        areaCode += area[i].split("-")[0] + "," ;
		   	  			        areaName += area[i].split("-")[1] + "," ;
		   	  			    }
		   	    		}
					   service.setCountryCode(areaCode);
					   service.setCountryName(areaName);
				   }

	            }
			   service.setCreateTime(currentDate);
			   service.setCreater(loginAuthDto.getUserCode());
			   service.setUpdateTime(currentDate);
			   service.setUpdater(loginAuthDto.getUserCode());
			   service.setStatus("1"); /** 2022/02/25 0025 10:00 【2.2-服务包配置需求】救援商编辑：优化保存操作，给状态status赋值1-有效，即启用  */
			   serviceProviderDao.insertServiceProvider(service);
			   String id=service.getId()+"";
			   List<DynamicItem> list=service.getDynamicItem();
			   if(!PublicUtil.isEmpty(service.getAddrCountyValue())) {
				   String[] aountyAdd=service.getAddrCountyValue().split(",");
				   for(int i = 0; i < aountyAdd.length; i++) {
					   ServiceProviderCountryEntity countryEntity=new ServiceProviderCountryEntity();
					   countryEntity.setYwid(id);
					   countryEntity.setCreateTime(currentDate);
					   countryEntity.setCreater(loginAuthDto.getUserCode());
					   countryEntity.setUpdateTime(currentDate);
					   countryEntity.setUpdater(loginAuthDto.getUserCode());
					   countryEntity.setCountryAll(aountyAdd[i]);
					   countryEntity.setCountryCode(aountyAdd[i].split("-")[0] );
					   countryEntity.setCountryName(aountyAdd[i].split("-")[1] );
					   serviceProviderCountryDao.insertServiceProviderCountry(countryEntity);
	   	    		}
			   }
			   for(int i=0;i<list.size();i++) {
					ServiceProviderDataEntity data=new ServiceProviderDataEntity();
					data.setUrl(list.get(i).getUrl());;
					data.setUrlType(list.get(i).getUrlType());
					data.setYwid(id);
					data.setCreateTime(currentDate);
					data.setCreater(loginAuthDto.getUserCode());
					data.setUpdateTime(currentDate);
					data.setUpdater(loginAuthDto.getUserCode());
					serviceProviderDataDao.insertServiceProviderData(data);
			   }
			}
		}else {
			/** 2022/02/25 0025 10:00 【2.2-服务包配置需求】救援商编辑  */
			// 查一个救援商
			ServiceProviderEntity dbServiceProviderEntity = serviceProviderDao.queryById(Integer.valueOf(service.getId().toString()));
			List<ServiceProviderEntity> serviceProviderEntityList = serviceProviderDao.selectServiceName(service);
			boolean remove = serviceProviderEntityList.remove(dbServiceProviderEntity); // list中出去根据id查询到的救援商，若还有，则判断为重复

			if(serviceProviderEntityList != null && serviceProviderEntityList.size() > 0) {
				throw new UacBizException(ErrorCodeEnum.CHANNE10011025, service.getServiceName());
			} else {
				String urlType=	removaDuplicate(service.getDynamicItem()); // 判断接口是否重复
				if("1".equals(urlType)) {
					throw new UacBizException(ErrorCodeEnum.CHANNE10011026, "");
				}
				if (!PublicUtil.isEmpty(service.getAddrCounty())) {
					if(!PublicUtil.isEmpty(service.getAddrCounty().get("province"))) {
						String[] province=service.getAddrCounty().get("province").split(",");
						String provinceName="";
						String provinceCode="";
						for(int i = 0; i < province.length; i++) {
							if(i == province.length-1){
								provinceCode +=province[i].split("-")[0] ;
								provinceName +=province[i].split("-")[1] ;
							}else{
								provinceCode += province[i].split("-")[0] + "," ;
								provinceName += province[i].split("-")[1] + "," ;
							}
						}
						dbServiceProviderEntity.setProvinceCode(provinceCode);
						dbServiceProviderEntity.setProvinceName(provinceName);
					} else {
						dbServiceProviderEntity.setProvinceCode(null);
						dbServiceProviderEntity.setProvinceName(null);
					}
					if(!PublicUtil.isEmpty(service.getAddrCounty().get("city"))) {
						String[] city=service.getAddrCounty().get("city").split(",");

						String cityName="";
						String cityCode="";
						for(int i = 0; i < city.length; i++) {
							if(i == city.length-1){
								cityCode +=city[i].split("-")[0] ;
								cityName +=city[i].split("-")[1] ;
							}else{
								cityCode += city[i].split("-")[0] + "," ;
								cityName += city[i].split("-")[1] + "," ;
							}
						}
						dbServiceProviderEntity.setCityCode(cityCode);
						dbServiceProviderEntity.setCityName(cityName);
					} else {
						dbServiceProviderEntity.setCityCode(null);
						dbServiceProviderEntity.setCityName(null);
					}
					if(!PublicUtil.isEmpty(service.getAddrCounty().get("area"))) {
						String[] area=service.getAddrCounty().get("area").split(",");

						String areaName="";
						String areaCode="";
						for(int i = 0; i < area.length; i++) {
							if(i == area.length-1){
								areaCode +=area[i].split("-")[0] ;
								areaName +=area[i].split("-")[1] ;
							}else{
								areaCode += area[i].split("-")[0] + "," ;
								areaName += area[i].split("-")[1] + "," ;
							}
						}
						dbServiceProviderEntity.setCountryCode(areaCode);
						dbServiceProviderEntity.setCountryName(areaName);
					} else {
						dbServiceProviderEntity.setCountryCode(null);
						dbServiceProviderEntity.setCountryName(null);
					}

				}

				dbServiceProviderEntity.setClientId(service.getClientId());
				dbServiceProviderEntity.setServiceName(service.getServiceName());
				dbServiceProviderEntity.setServiceCode(service.getServiceCode());
				dbServiceProviderEntity.setShiftName(service.getShiftName());
				dbServiceProviderEntity.setServiceItem(service.getServiceItem());
				dbServiceProviderEntity.setPk(service.getPk());
				dbServiceProviderEntity.setSk(service.getSk());
				dbServiceProviderEntity.setStatus(service.getStatus());

				dbServiceProviderEntity.setUpdateTime(currentDate);
				dbServiceProviderEntity.setUpdater(loginAuthDto.getUserCode());
				serviceProviderDao.update(dbServiceProviderEntity);

				String id = Long.toString(service.getId());
				List<DynamicItem> list = service.getDynamicItem();

				// 删除已有的country，将新的重新保存
				int deleteCountry = serviceProviderCountryDao.deleteByYwid(id);
				if(!PublicUtil.isEmpty(service.getAddrCountyValue())) {
					String[] aountyAdd=service.getAddrCountyValue().split(",");
					for(int i = 0; i < aountyAdd.length; i++) {
						ServiceProviderCountryEntity countryEntity=new ServiceProviderCountryEntity();
						countryEntity.setYwid(id);
						countryEntity.setCreateTime(currentDate);
						countryEntity.setCreater(loginAuthDto.getUserCode());
						countryEntity.setUpdateTime(currentDate);
						countryEntity.setUpdater(loginAuthDto.getUserCode());
						countryEntity.setCountryAll(aountyAdd[i]);
						countryEntity.setCountryCode(aountyAdd[i].split("-")[0] );
						countryEntity.setCountryName(aountyAdd[i].split("-")[1] );
						serviceProviderCountryDao.insertServiceProviderCountry(countryEntity);
					}
				}

				// 删除已有的data，将新的重新保存
				int deleteData = serviceProviderDataDao.deleteByYwid(id);
				for(int i=0; i<list.size(); i++) {
					ServiceProviderDataEntity data=new ServiceProviderDataEntity();
					data.setUrl(list.get(i).getUrl());;
					data.setUrlType(list.get(i).getUrlType());
					data.setYwid(id);
					data.setCreateTime(currentDate);
					data.setCreater(loginAuthDto.getUserCode());
					data.setUpdateTime(currentDate);
					data.setUpdater(loginAuthDto.getUserCode());
					serviceProviderDataDao.insertServiceProviderData(data);
				}

			}
		}
	}





	@Override
	public String getServiceName(String serviceName, String id) {
		// 查一个救援商
		ServiceProviderEntity dbServiceProviderEntity = (id != null && !"".equals(id) && !"null".equals(id)) ? serviceProviderDao.queryById(Integer.valueOf(id)) : null;

		ServiceProviderEntity service = new ServiceProviderEntity();
		service.setServiceName(serviceName);
		List<ServiceProviderEntity> serviceProviderEntityList = serviceProviderDao.selectServiceName(service);

		boolean remove = serviceProviderEntityList.remove(dbServiceProviderEntity); // list中出去根据id查询到的救援商，若还有，则判断为重复

		String result="";
		if(serviceProviderEntityList != null && serviceProviderEntityList.size() > 0){
			result = "1";
		} else {
			result = "0";
		}
		return result;
	}

	@Override
	public String getServiceCode(String serviceCode, String id) {
		// 查一个救援商
		ServiceProviderEntity dbServiceProviderEntity = (id != null && !"".equals(id) && !"null".equals(id)) ? serviceProviderDao.queryById(Integer.valueOf(id)) : null;

		ServiceProviderEntity service = new ServiceProviderEntity();
		service.setServiceCode(serviceCode);
		List<ServiceProviderEntity> serviceProviderEntityList = serviceProviderDao.selectServiceName(service);

		boolean remove = serviceProviderEntityList.remove(dbServiceProviderEntity); // list中出去根据id查询到的救援商，若还有，则判断为重复

		String result="";
		if(serviceProviderEntityList != null && serviceProviderEntityList.size() > 0) {
			result = "1";
		} else {
			result = "0";
		}
		return result;
	}















	public String  removaDuplicate(List<DynamicItem> list){
		String temp = "";
        for (int i = 0; i < list.size() - 1; i++){
            temp = list.get(i).getUrlType();
            for (int j = i + 1; j < list.size(); j++) {
                if (temp.equals(list.get(j).getUrlType())){
                    System.out.println("第" + (i + 1) + "个跟第" + (j + 1) + "个重复，值是：" + temp);
                    return "1";
                }
            }
        }
		return "0";
	}



	public  String getSqlInString(List<String> values){
		if(PublicUtil.isEmpty(values) ) return "";
		StringBuffer res =  new StringBuffer("(");
		int firstFlag = 1;
		for(String val : values){
			if(firstFlag == 1){
				res.append("'").append(val).append("'");
				firstFlag = 0;
			}else{
				res.append(",'").append(val).append("'");
			}
		}
		res.append(")");
		return res.toString();
	}


	/**
	 *
	 * @author WANGCONG
	 * 2021年10月18日下午7:24:15
	 * @desc 根据省市区、服务类型匹配服务商信息
	 */
	@Override
	public List<ServiceProviderEntity> choiceServicer(Map<String, Object> paramsMap) {
		return serviceProviderDao.choiceServicer(paramsMap);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年10月19日下午1:36:12
	 * @desc 根据map参数查询实体信息
	 */
	@Override
	public ServiceProviderEntity findProviderByParam(Map<String, String> servicerParam) {
		return serviceProviderDao.findProviderByParam(servicerParam);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年10月20日下午1:06:31
	 * @desc 手动派单、改派，根据所选服务单的服务类型、省市区集合匹配服务商
	 */
	@Override
	public List<ServiceProviderEntity> findMatchServicer(Map<String, Object> params) {
		return serviceProviderDao.findMatchServicer(params);
	}



	/**
	 *
	 * @author WANGCONG
	 * 2021年10月20日下午4:05:15
	 * @desc 根据服务商Id查询接口地址信息
	 */
	@Override
	public List<ServiceProviderDataEntity> queryListByYwId(String servicerId) {
		return serviceProviderDataDao.queryListByYwId(servicerId);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年10月20日下午6:36:45
	 * @desc 根据主键查询服务商
	 */
	@Override
	public ServiceProviderEntity queryById(Integer id) {
		return serviceProviderDao.queryById(id);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年10月21日上午10:39:51
	 * @desc 不带分页查询列表
	 */
	@Override
	public List<ServiceProviderEntity> findList() {
		return serviceProviderDao.findList();
	}

	@Override
	public List<ServiceProviderEntity> getAllServiceName() {
		return serviceProviderDao.getAllServiceName();
	}


	/**
	 * @param id 救援商主键
	 * @param status 目标状态
	 * @return
	 * @description 修改救援商状态【2.2-服务包配置需求】
	 * @author wkangle
	 * @time 2022-02-25 09:48:51
	 * @exception/throws
	 */
	@Override
	public Map<String, String> switchStatus(Long id, String status) {
		Map<String, String> result = new HashMap<>();
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		ServiceProviderEntity queryById = serviceProviderDao.queryById(Integer.valueOf(id.toString()));
		if (PublicUtil.isEmpty(queryById)) {
			result.put("code", "0001");
			result.put("message", "救援商不存在");
			return result;
		}
		if ("1".equals(status)) { // 启用
			String dbStatus = queryById.getStatus();
			if ("1".equals(dbStatus)) {
				result.put("code", "0001");
				result.put("message", "救援商(" + queryById.getServiceName() + ")已是启用状态");
				return result;
			} else {
				try {
					queryById.setStatus("1");
					serviceProviderDao.updateById(queryById);

					result.put("code", "0000");
					result.put("message", "救援商(" + queryById.getServiceName() + ")启用成功");
					return result;
				} catch (Exception e) {
					e.printStackTrace();
					result.put("code", "0001");
					result.put("message", "救援商(" + queryById.getServiceName() + ")启用失败，原因：" + e.getMessage());
					return result;
				}
			}
		} else { // 禁用
			String dbStatus = queryById.getStatus();
			if ("0".equals(dbStatus)) {
				result.put("code", "0001");
				result.put("message", "救援商(" + queryById.getServiceName() + ")已是禁用状态");
				return result;
			} else {
				try {
					queryById.setStatus("0");
					serviceProviderDao.updateById(queryById);

					result.put("code", "0000");
					result.put("message", "救援商(" + queryById.getServiceName() + ")禁用成功");
					return result;
				} catch (Exception e) {
					e.printStackTrace();
					result.put("code", "0001");
					result.put("message", "救援商(" + queryById.getServiceName() + ")禁用失败，原因：" + e.getMessage());
					return result;
				}
			}
		}
	}

	/**
	 * @param id 救援商主键id
	 * @return
	 * @description 根据救援商主键id查询一个，用于修改回显【2.2-服务包配置需求】
	 * @author wkangle
	 * @time 2022-03-03 14:13:03
	 * @exception/throws
	 */
	@Override
	public ServiceProviderVo queryOne(Long id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		ServiceProviderEntity entity = this.getOneByParams(params);

		ServiceProviderVo vo = new ServiceProviderVo();
		vo.setId(entity.getId());
		vo.setClientId(entity.getClientId());
		vo.setServiceName(entity.getServiceName());
		vo.setServiceCode(entity.getServiceCode());
		vo.setShiftName(entity.getShiftName());
		vo.setServiceItem(entity.getServiceItem());
		vo.setPk(entity.getPk());
		vo.setSk(entity.getSk());
		vo.setStatus(entity.getStatus());
		vo.setProvinceCode(entity.getProvinceCode());
		vo.setCityCode(entity.getCityCode());
		vo.setCountryCode(entity.getCountryCode());
		vo.setProvinceName(entity.getProvinceName());
		vo.setCityName(entity.getCityName());
		vo.setCountryName(entity.getCountryName());

		vo.setIsDelete(entity.getIsDelete());
		vo.setCreater(entity.getCreater());
		vo.setCreateTime(entity.getCreateTime());
		vo.setUpdater(entity.getUpdater());
		vo.setUpdateTime(entity.getUpdateTime());

		List<ServiceProviderDataEntity> serviceProviderDataEntityList = serviceProviderDataDao.queryListByYwId(id.toString());
		vo.setServiceProviderDataEntityList(serviceProviderDataEntityList);
		return vo;
	}


}
